﻿using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Trentacular.SharePoint.Web.UI
{
    /// <summary>
    /// Base class that custom SharePoint User Controls may inherit from.
    /// </summary>
    public abstract class BaseSPUserControl : UserControl
    {
        private SPContext _spContext;

        /// <summary>
        /// Gets the current SPContext.
        /// </summary>
        /// <value>The current SPContext.</value>
        protected SPContext SPContext
        {
            get
            {
                if (_spContext == null)
                    _spContext = SPContext.Current;
                return _spContext;
            }
        }

        /// <summary>
        /// Gets the current SPWeb.
        /// </summary>
        /// <value>The current SPWeb.</value>
        protected SPWeb Web { get { return SPContext.Web; } }

        /// <summary>
        /// Gets the current user.
        /// </summary>
        /// <value>The current user.</value>
        protected SPUser CurrentUser { get { return Web.CurrentUser; } }

        /// <summary>
        /// Performs a redirect to the page specified by the Source querystring
        /// parameter or to the current page.
        /// </summary>
        protected virtual void SmartRedirect()
        {
            SmartRedirect(null);
        }

        /// <summary>
        /// Performs a redirect to the page specified by the Source querystring
        /// parameter or to the specified url.
        /// </summary>
        /// <param name="defaultUrl">The default URL.</param>
        protected virtual void SmartRedirect(string defaultUrl)
        {
            if (defaultUrl == null)
                defaultUrl = Request.RawUrl;

            SPUtility.Redirect(defaultUrl, SPRedirectFlags.UseSource, Context);
        }
    }
}
